package com.wxmit.ot.gen.controller;

import com.wxmit.ot.base.ApiResult;
import com.wxmit.ot.exception.BaseException;
import com.wxmit.ot.gen.domain.dto.TemplateTestDto;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import java.io.IOException;

/**
 * TemplateTestOnlineController
 *
 * @author huangxiong
 * @version V1.0
 * @date 2023/3/13 11:22
 */
@RestController
@RequestMapping("/template")
@Slf4j
@AllArgsConstructor
public class TemplateTestOnlineController {

    private final FreeMarkerConfig freeMarkerConfig;

    @PostMapping("/testOnline")
    public ApiResult<String> testOnline(@RequestBody @Validated TemplateTestDto templateTestDto){
        try {
            String code =  FreeMarkerTemplateUtils.processTemplateIntoString(new Template("模版在线测试", templateTestDto.getCode(), freeMarkerConfig.getConfiguration()), templateTestDto.getParam());
            return ApiResult.successWithData(code);
        } catch (IOException e) {
            throw new BaseException("模版在线测试 代码生成异常",e);
        }catch (TemplateException e){
            throw new BaseException("模版在线测试 代码生成异常: ${e.getFTLInstructionStack()}",e);
        }

    }
}
